import tkinter
from PIL import Image, ImageTk
import tkmacosx
from tkinter.messagebox import *
import pymysql
import gui_index
import gui_register
import time
import gui_admin


def check_login_db(usr, passwd):
    # 连接mysql数据库
    if usr=="root" and passwd=="root":
        gui_admin.create_one()
        return 0
    db = pymysql.connect(host='180.102.129.53',user='root',passwd='520hhy',db='hhy',charset='utf8')
    cursor = db.cursor()
    sql = "select * from login where username ='{}'".format(usr)
    cursor.execute(sql)
    res = cursor.fetchall()
    if len(res) == 0:
        showinfo("showinfo","查无此人")
        return "查无此人"
    else:
        # i[0]为账号，i[1]为密码，如果没查到 res是空的
        for i in res:
            if passwd == i[1]:
                log.destroy()
                whattime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                sql = """insert into admin(user,login_time) values("{}","{}");""".format(usr, str(whattime))
                print(sql)
                cursor.execute(sql)
                db.commit()
                gui_index.create_index(usr)
                return "登陆成功"
            else:
                showinfo("showinfo", "密码错误")
                return "密码错误"


def resize(w_box, h_box, pil_image):
    # 参数是：要适应的窗口宽、高、Image.open后的图片
    # 处理自适应大小
    w, h = pil_image.size  # 获取图像的原始大小
    f1 = 1.0 * w_box / w
    f2 = 1.0 * h_box / h
    factor = min([f1, f2])
    width = int(w * factor)
    height = int(h * factor)
    return pil_image.resize((width, height), Image.ANTIALIAS)


def create():
    log.destroy()
    gui_register.create_reg()


if __name__ == '__main__':
    log = tkinter.Tk()
    log.title("数据可视化平台登陆")
    log.geometry('300x200')
    # can = tkinter.Canvas(log, height=200, width=200)
    img1 = Image.open(r'../non/1.png')
    img1 = resize(72, 72, img1)
    img2 = ImageTk.PhotoImage(img1)
    img_label = tkinter.Label(log, image=img2)
    img_label.pack()
    username_str = tkinter.StringVar()
    username = tkinter.Entry(bg="white", fg="black", textvariable=username_str)
    username_str.set("hhy")
    password_str = tkinter.StringVar()
    password = tkinter.Entry(bg="white", fg="black", textvariable=password_str,show='*')
    password_str.set("foryou")
    username.pack()
    password.pack()
    # window可能会用到
    # login = tkinter.Button(log, text="登陆",bg="green",fg="black")
    button_text = tkinter.StringVar()
    button_text.set("登陆")
    login = tkmacosx.Button(log, textvariable=button_text, bg="#339933",fg="white",width=180,height=40,command=lambda :check_login_db(username_str.get(),password_str.get()))
    reg = tkmacosx.Button(log, text="点击注册",width=180,height=30,command=lambda :create())
    login.pack()
    reg.pack()
    log.mainloop()
